package com.ruoyi.web.controller.system.api.cc;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.interceptor.Authentication;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.Login;
import com.ruoyi.system.api.domain.User;
import com.ruoyi.system.api.service.CcService;
import com.ruoyi.system.api.service.LoginService;
import com.ruoyi.system.domain.SysUser;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @ClassName LoginController
 * @Description: 用户登陆
 * @Author shihx
 * @Date 2020/2/24
 * @Version V1.0
 **/
@Api(tags="用户登陆、授权")
@Controller
@RequestMapping("/api/cc/login")
public class LoginController  extends BaseController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private CcService ccService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private Global global;

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    /**
     * 登陆接口
     * @methodName: login
     * @description: TODO
     * @param login
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: shihx
     * @date: 2020/2/24 16:01
    **/
    @PostMapping("/login")
    @ResponseBody
    @Authentication(tokenRequired = false, signRequired = true)
    @ApiOperation(value = "用户登陆接口", httpMethod = "POST", notes = "用户登陆接口")
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功",response = User.class)
    })
    @Transactional(rollbackFor = Exception.class)
    public ResponseWithData<?> login(@RequestBody Login login){
        try {
            SysUser sysUser = new SysUser();
            sysUser.setSalt(ShiroUtils.randomSalt());
            String email = login.getEmail();
            if(StringUtils.isNotEmpty(email) && !email.contains("@")){
                email+= "@thermofisher.com";
            }
            login.setEmail(email);
//            sysUser.setPassword(passwordService.encryptPassword(login.getEmail(), global.getDefaultPw(), sysUser.getSalt()));
            String loginEmail= login.getEmail();
            String password= loginEmail.substring(0,loginEmail.indexOf("@"))+"8!@#";
            sysUser.setPassword(passwordService.encryptPassword(loginEmail, password, sysUser.getSalt()));
            return loginService.login(login, sysUser);
        }catch (Exception e){
            e.printStackTrace();
            log.error("程序异常{}", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 获取用户授权（ACCESS_TOKEN）接口
     * @methodName: authorization
     * @description: TODO
     * @param ApiKey
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: shihx
     * @date: 2020/2/28 9:57
    **/
    @GetMapping("/authorization")
    @ResponseBody
    @Authentication(tokenRequired = false, signRequired = true)
    @ApiOperation(value = "获取用户授权（ACCESS_TOKEN）接口", httpMethod = "GET", notes = "获取用户授权（ACCESS_TOKEN）接口")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户唯一标识APIKEY", name = "ApiKey", required = true, defaultValue = "10009", dataType = "String", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> authorization(@RequestParam(value="ApiKey",required=true) String ApiKey){
        try {
            return loginService.authorization(ApiKey);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    @GetMapping("/authorizationApp")
    @ResponseBody
    @Authentication(tokenRequired = false, signRequired = true)
    @ApiOperation(value = "获取用户授权（ACCESS_TOKEN）接口 APP端使用", httpMethod = "GET", notes = "获取用户授权（ACCESS_TOKEN）接口 APP端使用")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户唯一标识APIKEY", name = "ApiKey", required = true, defaultValue = "10009", dataType = "String", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> authorizationApp(@RequestParam(value="ApiKey",required=true) String ApiKey){
        try {
            return loginService.authorizationApp(ApiKey);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    @GetMapping("/syncTLServiceData")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "2.2同步TL待指派服务信息接口", httpMethod = "GET", notes = "2.2同步TL待指派服务信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "时间戳", name = "timeStamp", required = true, defaultValue = "1514736000000", dataType = "Long", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> syncTLServiceData(@RequestParam(value="timeStamp",required=true) Long timeStamp){
        try {
            return ccService.syncTLServiceData(timeStamp);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }


}
